package top.riske.animalhazardassessment.common.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import top.riske.animalhazardassessment.common.DTO.JwtDto;

import java.io.IOException;

/**
 * 用户权限过滤器，保护所有/protected/user开头的路径
 * created by vital on 2025/3/1 下午3:12
 */
@Slf4j
public class UserRoleFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("UserRoleFilter过滤器执行");

        // 判断是否是http请求
        if(!(servletRequest instanceof HttpServletRequest)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 强制转换为http请求
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // 从请求头中提取身份信息
        JwtDto jwtDto = (JwtDto) httpRequest.getAttribute(AuthorizationFilter.AUTHORIZATION_DATA_HEADER);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("UserRoleFilter初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        log.info("UserRoleFilter销毁");
        Filter.super.destroy();
    }
}
